import os
import cgi
import random

from google.appengine.ext.webapp import template

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Link(db.Model):
    author = db.UserProperty()
    original = db.StringProperty(multiline=False)
    modified = db.StringProperty(multiline=False)
    clicks = db.IntegerProperty()
    date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
    def get(self):
        path = self.request.path
        ## self.response.out.write(path);        
        if path == '/':
            self.showMainPage()
        else:
            self.showUserUrlPage(path.lstrip('/'))

    def showMainPage(self):
        link_query = Link.all().order('-date')
        links = link_query.fetch(10)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'links': links,
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'ui/index.html')
        self.response.out.write(template.render(path, template_values))

    def showUserUrlPage(self, url_token):
        link = Linker().queryLink(url_token)
        ## TODO: show an error page if no link is found
        content_url = 'http://localhost:8080/ads'
        if link:
            content_url = link.original

            if not content_url.startswith('http://'):
                content_url = 'http://%s' % content_url

        template_values = {
            'url': content_url,
        }

        path = os.path.join(os.path.dirname(__file__), 'ui/content_page.html')
        self.response.out.write(template.render(path, template_values))

class Converter(webapp.RequestHandler):
    def post(self):

        author = None
        if users.get_current_user():
            author = users.get_current_user()
        url = self.request.get('content')
        Linker().createLink(url, author)
        self.redirect('/')

class UserStats(webapp.RequestHandler):
    def get(self):
      user = self.request.get("user")
      if not user:
        self.response.out.write('User param not set!')
        return

      # The Query interface prepares a query using instance methods.
      q = Link.all()
      q.filter("author =", users.User(user))

      ## TODO: should be fetchAll()
      links = q.fetch(100)

      total_clicks = 0
      for link in links:
        total_clicks += link.clicks

      template_values = {
          'user': user,
          'links': '%d' % len(links),
          'clicks': '%d' % total_clicks,
      }

      path = os.path.join(os.path.dirname(__file__), 'ui/u_page.html')
      self.response.out.write(template.render(path, template_values))

class Linker(object):
    _CHARSEQ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789'

    def createLink(self, url, user):
        link = Link()
        link.author = user

        link.original = url
        ## TODO: change localhost to the server name
        link.modified = 'http://localhost:8080/' + self.randomToken()
        link.clicks = 0
        link.put()
        return link

    def queryLink(self, url_token):
      token_url = 'http://localhost:8080/%s' % url_token

      # The Query interface prepares a query using instance methods.
      q = Link.all()
      q.filter("modified =", token_url)
      q.order("-date")

      links = q.fetch(1)
 
      if links:
        link = links[0]
        link.clicks += 1
        link.put()
        return link
      else:
        return None          
        
    def randomToken(self):
        token = ''
        for i in range(0, 6):
            token += random.choice(self._CHARSEQ)
        return token

class DummyAdsPage(webapp.RequestHandler):
    def get(self):
      self.response.out.write("<h1 align=center><font color=red size=24>Ads page!!</font></h1>")

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/convert', Converter),
                                      ('/u', UserStats),
                                      ('/ads', DummyAdsPage),
                                      ('/.*', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
